'use strict';

const semver = require('semver'); // 比较node版本
const colors = require('colors'); // 字体颜色
const log = require('@gok-cli/log');
const LOWEST_NODE_VERSION = '12.0.0';

class Command {
    constructor(argv) {
        if (!argv) {
            throw new Error('参数不能为空！');
        }
        if (!Array.isArray(argv)) {
            throw new Error('参数必须为数组！');
        }
        if (argv.length < 1) {
            throw new Error('参数列表为空！');
        }
        this._argv = argv;
        let runner = new Promise((resolve, reject) => {
            let chain = Promise.resolve();
            chain = chain.then(() => this.checkNodeVersion()); // 查node版本
            chain = chain.then(() => this.initArgs()); // 初始化参数
            chain = chain.then(() => this.init());
            chain = chain.then(() => this.exec());
            chain.catch(err => {
                log.error(err.message)
            })
        })
    }

    initArgs() {
        this._cmd = this._argv[this._argv.length - 1];
        this._argv = this._argv.slice(0, this._argv.length - 1);
    }

    // 检查node版本号
    checkNodeVersion() {
        const currentVersion = process.version; // 当前版本号
        const lowestVersion = LOWEST_NODE_VERSION; // 最低版本号
        if(!semver.gte(currentVersion, lowestVersion)) {
            throw new Error(colors.red(`gok-cli 需要安装 v${lowestVersion} 以上版本的Node.js`))
        }
    } 
    init() {
        throw new Error('init必须实现！')
    }
    exec() { 
        throw new Error('exec必须实现！')
    }
}

module.exports = Command;
